#!/bin/bash

BASE_HOME=$(dirname "$0")
source ${BASE_HOME}/common_setup  # Loading the common code section from 'common_setup', and 'common_setup' in turn loads the shared functions from 'common_functions'.

log_info "Begin Keepalived(vrrp_scripts) check mysql"

# If the write vip in this node and this node is master node
WVIP_COUNT=$(ip addr | grep -c "${WRITE_VIP}")

if [ "${WVIP_COUNT}" -eq 1 ]; then
    log_warn "VIP ${WRITE_VIP} exists on local host  ${LOCAL_HOST} so this node mysql is master !"
    log_info "VIP $(ip addr | grep "${WRITE_VIP}")"
else
    log_warn "VIP ${WRITE_VIP} not exists on local host  ${LOCAL_HOST} so this node mysql node is slave!"
fi

# Check mysql is alived function
check_mysql_alive() {
    local i=0
    local COUNTER_RES=0
    local MYSQL_ALIVE_CHKLOG="${LOGFILE_PATH}/mysql_alive_$(date +%Y%m%d%H%M%S)$RANDOM"
    MYSQL_ALIVED=0

    log_info "CMD: nohup ${MYSQL_CMD} -u${MYSQL_HA_USER} -p\${MYSQL_HA_PWD} -P${MYSQL_PORT} -h${LOCAL_HOST} --protocol=tcp -N -L -s  -e \"${CHECK_SQL}\" > ${MYSQL_ALIVE_CHKLOG} 2>/dev/null &"
    nohup ${MYSQL_LOCAL_CMD} -N -L -s -e "${CHECK_SQL}" > "${MYSQL_ALIVE_CHKLOG}" 2>/dev/null &

    while [ $i -lt ${CHECK_TIME} ]; do
        i=$((i + 1))
        sleep 1
        if [ -s "${MYSQL_ALIVE_CHKLOG}" ]; then
            COUNTER_RES=$(cat "${MYSQL_ALIVE_CHKLOG}" | wc -l)
            COUNTER_RES=${COUNTER_RES:-0}
            if [ ${COUNTER_RES} -gt 0 ]; then
                MYSQL_ALIVED=1
				log_info "CHECK_SQL result is:   $(cat ${MYSQL_ALIVE_CHKLOG})"
                rm -f "${MYSQL_ALIVE_CHKLOG}"
                break
            fi
        fi
    done
}

ic=1
while [ $ic -le ${CHECK_COUNT} ]; do
    log_info "Start a check to see if MySQL is alive!"
    check_mysql_alive
    if (( ${MYSQL_ALIVED} == 1 )); then
        log_info "Keepalived(vrrp_scripts):MySQL Database Server is running and check count is ${ic} !"
        log_info "End Keepalived(vrrp_scripts) check mysql with exit 0"
        exit 0
    else
        log_info "Keepalived(vrrp_scripts):MySQL Database Server is not running and check count is ${ic}!"
        if [ ${ic} -eq ${CHECK_COUNT} ]; then
            log_warn "Mysql is not running and started switch keepalived!"
            log_warn "End Keepalived(vrrp_scripts) check mysql with exit 1"
            exit 1
        fi
    fi
    ic=$((ic + 1))
done